package com.chenlehao.aop;

import com.alibaba.fastjson2.JSONObject;
import com.chenlehao.mapper.logMapper;
import com.chenlehao.pojo.successLog;
import com.chenlehao.utils.jwt;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect // AOP类
@Slf4j
public class logAspect {
    @Pointcut("@annotation(com.chenlehao.aop.MyLog)")
    private void pt() {}

    @Autowired
    private logMapper logMapper;
    @Autowired
    private jwt jwt;

    // 请求信息
    @Autowired
    private HttpServletRequest request;

    // 记录方法操作日志AOP
    @Around("pt()")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("验证登录逻辑");
        // 操作人ID - 当前登录员工ID
        // 获取请求头中的jwt令牌, 解析令牌
        String token = request.getHeader("token");
        Claims claims = jwt.parseJwt(token);

        // 操作人
        String username = claims.get("username").toString();

        // 操作时间
        LocalDateTime operateTime = LocalDateTime.now();

        // 操作类名
        String className = joinPoint.getTarget().getClass().getName();

        // 操作方法名
        String methodName = joinPoint.getSignature().getName();

        log.info("123");

        // 操作方法参数
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);

        long begin = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();

        // 方法返回值
        String returnValue = JSONObject.toJSONString(result);

        // 操作耗时
        Long costTime = end - begin;

        successLog successLog = new successLog(username,operateTime, className, methodName, methodParams, returnValue, costTime);

        logMapper.insertLog(successLog);

        return result;
    }
}
